package com.chanyachting.emall.action.ad;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.chanyachting.emall.domain.Ad;
import com.chanyachting.emall.form.AdForm;
import com.chanyachting.emall.util.DateUtil;
import com.chanyachting.emall.util.MyFile;
import com.chanyachting.emall.util.RequestUtil;

public class AdAction extends DispatchAction {

	
	public ActionForward create(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		if(request.getMethod().equals("POST")){
			
			AdForm adform=(AdForm)form;
			
			if(adform.validate(mapping, request).isEmpty()){
				
				Ad ad=new Ad();
				
				BeanUtils.copyProperties(ad, adform);
				
				String imgUrl=MyFile.saveFileForm(adform.getFile(), request);
				
				if(imgUrl!=null) ad.setImgUrl(imgUrl);
				
				ad.setClickNumber(0);
				ad.setCreateDate(DateUtil.getDate());
				
				if(ad.save()){
					
					ru.setSuccessMsg();
					
				}else ru.setFailMsg();
				
			}
			
		}

		return mapping.findForward("create");
	}
	
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		int id=Integer.parseInt(ru.getParameter("id", "0"));
		
		if(request.getMethod().equals("POST")){
			
			AdForm adform=(AdForm)form;
			
			if(adform.validate(mapping, request).isEmpty()){
				
				Ad ad=new Ad(id);
				
				BeanUtils.copyProperties(ad, adform);
				
				String imgUrl=MyFile.saveFileForm(adform.getFile(), request);
				
				if(imgUrl!=null) ad.setImgUrl(imgUrl);
				
				if(ad.update()){
					
					ru.setSuccessMsg();
					
				}else ru.setFailMsg();
				
			}
			
		}
		
		ru.setAttribute("ad", new Ad(id));
		
		return mapping.findForward("update");
	}
	
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		int id=Integer.parseInt(ru.getParameter("id", "0"));
		
		Ad ad=new Ad(id);
		
		if(ad.delete()){
			
			ru.setSuccessMsg();
		}else{
			
			ru.setFailMsg();
		}
		
		return mapping.findForward("delete");
	}
	
	
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		new RequestUtil(request).setAttribute("adList", Ad.list());
		
		return mapping.findForward("list");
	}
	
	

}
